
#include <thread>
#include <nanomsg/nn.h>
#include <nanomsg/reqrep.h>

#include "rpc_msg.h"
#include "rpc_server.h"

int32_t RPCServer::Init(const char* pcURL)
{
    m_iNNSock = nn_socket(AF_SP, NN_REP);
    if (m_iNNSock == -1)
    {
        return -1;
    }

    return nn_bind(m_iNNSock, pcURL);
}

int32_t RPCServer::Start()
{
    if (m_iNNSock == -1)
    {
        return -1;
    }

    for (;;)
    {
        RpcRequest stReq;
        int32_t iLen = nn_recv(m_iNNSock, &stReq, sizeof(stReq), 0);
        if (iLen == -1)
        {
            continue;
        }

        RpcReply stReply;
        m_Service.Call(stReq, stReply);

        //std::this_thread::sleep_for(std::chrono::seconds(10));
        if (nn_send(m_iNNSock, &stReply, sizeof(stReply), 0) == -1)
        {
            break;
        }
    }

    return 0;
}